<?php

namespace App\Admin\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Base\ServerList;
use App\Models\Base\StatHourOrder;
use App\Service\OrderService;
use Carbon\Carbon;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Layout\Content;

class StatOrderController extends Controller
{
    /**
     * Index interface.
     *
     * @return Content
     */
    public function index()
    {
        return Admin::content(function (Content $content) {
            $content->header(trans('game.order_stat'));
            $content->description(trans('game.order_trend'));
            $server = ServerList::all()->pluck('name', 'server_id');
            $date_time = request()->get('date_time');
            $server_id = request()->get('server_id') ?? 0;
            if (!$date_time) {
                $date_time = Carbon::now()->toDateString();
            }
            $list = $this->getOrderData($date_time, $server_id);
            if ($list) {
                $hours = array_column($list, 'hour');
                $amounts = array_column($list, 'amount');
                $order_numbers = array_column($list, 'order_number');
                $pay_people_numbers = array_column($list, 'pay_people_number');
            } else {
                $hours = $amounts = $order_numbers = $pay_people_numbers = [];
            }
            //充值档位
            $level_data = OrderService::getSomeDayPayLevelNumber($date_time, $server_id)->all();
            $level_amount = $level_number = [];
            if ($level_data) {
                $level_amount = array_column($level_data, 'amount');
                $level_number = array_column($level_data, 'number');
            }

            $data = [
                'server' => $server,
                'hours' => $hours,
                'amounts' => $amounts,
                'order_numbers' => $order_numbers,
                'pay_people_numbers' => $pay_people_numbers,
                'date_time' => $date_time,
                's_id' => $server_id,
                'level_amount' => $level_amount,
                'level_number' => $level_number,
            ];
            $content->body(view('admin.charts.order_timezone', $data));
        });
    }

    /**
     * [getOrderData 获取订单统计数据].
     *
     * @Author   王文凡
     * @DateTime 2018-05-25
     *
     * @version  1.0
     *
     * @return array
     */
    protected function getOrderData($date_time, $server_id)
    {
        if ($server_id) {
            $list = StatHourOrder::where('date_time', $date_time)
                ->where('server_id', $server_id)->selectRaw('hour,amount,order_number,pay_people_number')
                ->get()->toArray();
        } else {
            $list = StatHourOrder::where('date_time', $date_time)
                ->selectRaw('hour,sum(amount) as amount,sum(order_number) as order_number,sum(pay_people_number) as pay_people_number')
                ->groupBy('hour')->get()->toArray();
        }

        return $list;
    }
}
